package com.ktjy.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.ktjy.base.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

/**
 * WebBlockExceptionHandler
 *
 * @author LILIBO
 * @since 2025-06-07
 */
@Component
public class WebBlockExceptionHandler implements BlockExceptionHandler {

    /**
     * Sentinel流量监控Web接口异常处理器
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, String resourceName, BlockException e) throws Exception {
        response.setStatus(429); // 设置HTTP响应状态码为：429 Too Many Requests 表示请求过多
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(R.failure(2, "[Sentinel] 服务器繁忙，请稍后再试~")));
        response.getWriter().flush();
    }

}
